<template>
  <div>
    <Card title="管理员（拖动可以调整列宽和位置）">
      <template #extra>
        <a-button type="primary" @click="handleSelectCol(true)" :loading="loading">选择列</a-button>
      </template>
      <div class="w-full flex">
        <draggable
          v-model="managerList"
          :component-data="{
            type: 'transition-group',
            class: 'draggable-macro-icon-ctl-list',
          }"
          :animation="180"
          handle=".draggable-macro-icon-ctl"
          item-key="title"
          @change="handleChange(true)"
        >
          <template #item="{ element }">
            <div
              class="mb-2 cursor-pointer relative"
              :style="{
                backgroundColor: '#c6e1f4',
                borderTop: '1px solid #97bbd4',
                borderBottom: '1px solid #97bbd4',
                borderLeft: '1px solid #97bbd4',
                textAlign: 'center',
                height: '26px',
                lineHeight: '26px',
                '-moz-user-select': 'none',
                color: '#000',
                verticalAlign: 'middle',
                overflow: 'hidden',
                width: `${element.width}px`,
              }"
            >
              <div
                class="h-full w-full draggable-macro-icon-ctl flex justify-center items-center overflow-text"
              >
                <Tooltip>
                  <template #title>
                    <span> {{ element.title }}</span>
                  </template>
                  <span>
                    {{ element.title }}
                  </span>
                </Tooltip>
              </div>

              <div class="line" @mousedown="dragLine($event, element)"></div>
            </div>
          </template>
        </draggable>
        <Modal :width="1000" v-model:visible="open" @ok="handleSuccess" title="选择列">
          <div class="m-5 flex flex-wrap">
            <div v-for="(item, index) in columns" :key="index" class="mb-2 w-130px">
              <Checkbox v-model:checked="item.value">{{ item.title }}</Checkbox>
            </div>
          </div>
        </Modal>
      </div>
    </Card>
    <Card style="margin-top: 10px" title="普通用户（拖动可以调整列宽和位置）">
      <template #extra>
        <a-button type="primary" @click="handleSelectCol(false)" :loading="loading"
          >选择列</a-button
        >
      </template>
      <div class="w-full flex">
        <draggable
          v-model="everyList"
          :component-data="{
            type: 'transition-group2',
            class: 'draggable-macro-icon-ctl-list',
          }"
          :animation="180"
          handle=".draggable-macro-icon-ctl2"
          item-key="title"
          @change="handleChange(false)"
        >
          <template #item="{ element }">
            <div
              class="mb-2 cursor-pointer relative"
              :style="{
                backgroundColor: '#c6e1f4',
                borderTop: '1px solid #97bbd4',
                borderBottom: '1px solid #97bbd4',
                borderLeft: '1px solid #97bbd4',
                textAlign: 'center',
                height: '26px',
                lineHeight: '26px',
                '-moz-user-select': 'none',
                color: '#000',
                verticalAlign: 'middle',
                overflow: 'hidden',
                width: `${element.width}px`,
              }"
            >
              <div
                class="h-full w-full draggable-macro-icon-ctl2 flex justify-center items-center overflow-text"
              >
                <Tooltip>
                  <template #title>
                    <span> {{ element.title }}</span>
                  </template>
                  <span>
                    {{ element.title }}
                  </span>
                </Tooltip>
              </div>

              <div class="line" @mousedown="dragLine($event, element)"></div>
            </div>
          </template>
        </draggable>
      </div>
    </Card>
  </div>
</template>
<script lang="ts" setup>
  import { ref, onMounted } from 'vue';
  import draggable from 'vuedraggable';
  import { Checkbox, Card, Modal, Tooltip } from 'ant-design-vue';
  import {
    getConfigGetMyActionListCols,
    getConfigSetMyActionListCols,
  } from '/@/api/flowManage/flowManage';
  const loading = ref(false);
  const isForManager = ref(false);

  const managerList = ref<Recordable[]>([]);
  const everyList = ref<Recordable[]>([]);
  const handleSelectCol = (val) => {
    isForManager.value = val;
    open.value = true;
    const fields = isForManager.value
      ? managerList.value.map((item) => item.name)
      : everyList.value.map((item) => item.name);
    columns.value.forEach((item) => {
      if (fields.includes(item.name)) {
        item.value = true;
      } else {
        item.value = false;
      }
    });
  };

  const columns = ref<Recordable[]>([
    {
      title: '办理部门',
      name: 'depts',
      width: 120,
    },
    {
      title: '处理人',
      name: 'realName',
      width: 120,
    },
    {
      title: '转交人',
      name: 'privRealName',
      width: 120,
    },
    // {
    //   title: '代理人',
    //   name: 'isProxy',
    //   width: 120,
    // },
    {
      title: '任务',
      name: 'actionTitle',
      width: 120,
    },
    // {
    //   title: '到达状态',
    //   name: 'reachState',
    //   width: 120,
    // },
    {
      title: '收到时间',
      name: 'receiveDate',
      width: 120,
    },
    {
      title: '签收时间',
      name: 'readDate',
      width: 120,
    },
    {
      title: '实际处理者',
      name: 'checker',
      width: 120,
    },
    {
      title: '处理时间',
      name: 'checkDate',
      width: 120,
    },
    {
      title: '到期时间',
      name: 'expireDate',
      width: 120,
    },
    {
      title: '用时',
      name: 'workDuration',
      width: 120,
    },
    {
      title: '状态',
      name: 'checkStatusName',
      width: 120,
    },
    {
      title: '意见',
      name: 'result',
      width: 120,
    },
  ]);
  const open = ref(false);
  const handleSuccess = () => {
    if (isForManager.value) {
      let unDataList = columns.value.filter((item) => !item.value).map((el) => el.name);
      managerList.value = managerList.value.filter((item) => !unDataList.includes(item.name));
      const dataRefFields = managerList.value.map((item) => item.name);
      let dataList = columns.value.filter(
        (item) => item.value && !dataRefFields.includes(item.name),
      );
      managerList.value = [...managerList.value, ...dataList];
    } else {
      let unDataList = columns.value.filter((item) => !item.value).map((el) => el.name);
      everyList.value = everyList.value.filter((item) => !unDataList.includes(item.name));
      const dataRefFields = everyList.value.map((item) => item.name);
      let dataList = columns.value.filter(
        (item) => item.value && !dataRefFields.includes(item.name),
      );
      everyList.value = [...everyList.value, ...dataList];
    }
    open.value = false;
    handleChange(isForManager.value);
  };

  const fetch = async () => {
    loading.value = true;
    const data = await getConfigGetMyActionListCols({ isForManager: true });
    managerList.value = data && data.length ? data : [...columns.value];
    const data2 = await getConfigGetMyActionListCols({ isForManager: false });
    everyList.value = data2 && data2.length ? data2 : [...columns.value];
    loading.value = false;
  };

  const handleChange = (val) => {
    isForManager.value = val;
    setCols();
  };

  const setCols = async () => {
    try {
      const cols = isForManager.value
        ? managerList.value.map((item) => {
            return {
              title: item.title,
              name: item.name,
              width: item.width,
            };
          })
        : everyList.value.map((item) => {
            return {
              title: item.title,
              name: item.name,
              width: item.width,
            };
          });
      console.log('cols', cols);
      loading.value = true;
      await getConfigSetMyActionListCols({
        isForManager: isForManager.value,
        ary: cols,
      });
    } catch (error) {
      console.error('setCols', error);
    } finally {
      loading.value = false;
      fetch();
    }
  };

  const dragLine = (event, record) => {
    let orgWidth = event.clientX - record.width;
    document.onmousemove = (e) => {
      // console.log('e', e)
      //鼠标点击拖动时
      record.width = e.clientX - orgWidth;
    }; //绑定onmouseup
    document.onmouseup = () => {
      // 松开鼠标时
      if (record.width > 800) {
        record.width = 800;
      } else if (record.width < 40) {
        record.width = 40;
      }
      handleChange(isForManager.value);
      //解绑
      document.onmousemove = null;
      document.onmouseup = null;
    };
  };

  onMounted(fetch);
</script>
<style scoped>
  .draggable-macro-icon-ctl-list {
    display: flex;
    flex-wrap: wrap;
  }
  .line {
    position: absolute;
    width: 20px;
    height: 100%;
    right: -1px;
    z-index: 10;
    top: 0;
    /* height: calc(100% - 130px); */
    cursor: col-resize;
    overflow: hidden;
    z-index: 4;
    user-select: none;
    &::after {
      content: '';
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      display: block;
      margin: auto;
      width: 0;
      /* border: 1px dashed #ccc; */
    }
  }
  .overflow-text {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
</style>
